//
//  RXXKVideoView.m
//  RXXKVideo
//
//  Created by 星仔 on 2019/3/17.
//  Copyright © 2019年 rxx. All rights reserved.
//

#import "RXXKVideoView.h"
#import "RXXKVideoControlView.h"
#import "const.h"
#import "RXXKVideoModel.h"
#import "RXXKVideoControlView.h"
#import "RXXKVideoPlayer.h"
#import "Masonry.h"
#import "GKDYVideoViewModel.h"


@interface RXXKVideoView()<UIScrollViewDelegate,RXXKVideoPlayerDelegate,RXXKVideoControlViewDelegate>
//弱引用
@property (nonatomic, weak) UIViewController    *vc;
@property (nonatomic, assign) BOOL isPushed;
/**设置索引,也不一定和当前索引相同*/
@property (nonatomic, assign) NSInteger index;
/**当前播放索引*/
@property (nonatomic, assign) NSInteger currentPlayerIndex;
@property (nonatomic, strong) NSMutableArray *videos;
//创建三个控制视图,用于滑动切换
@property (nonatomic, strong) RXXKVideoControlView      *topVideoView;
@property (nonatomic, strong) RXXKVideoControlView      *ctrVideoView;
@property (nonatomic, strong) RXXKVideoControlView      *bomVideoView;
@property (nonatomic, strong) UIScrollView              *scrollView; //用于滚动视频
//滚动之前的播放状态
@property (nonatomic, assign) BOOL                      isPlaying_beforeScroll;
@property (nonatomic, copy)   NSString                  *currentPlayId;
@property (nonatomic, strong) RXXKVideoPlayer           *player;


@end

@implementation RXXKVideoView

#pragma mark - ♻️life cycle
- (instancetype)initWithVC:(UIViewController *)vc isPushed:(BOOL)isPushed{
    if (self = [super init]) {
        self.vc = vc;
        self.isPushed = isPushed;
        [self addSubview:self.scrollView];
        [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        
        if (!isPushed) {// 不是push进来的,push是进入个人内部的视频
            [self.viewModel refreshNewListWithSuccess:^(NSArray * _Nonnull list) {
                [self setUpVideoDatas:list atIndex:0];
            } failure:^(NSError * _Nonnull error) {
                NSLog(@"error-%@",error);
            }];
        }
        
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGFloat contentW =  CGRectGetWidth(self.scrollView.frame);
    CGFloat contentH = CGRectGetHeight(self.scrollView.frame);
    
    self.topVideoView.frame = CGRectMake(0, 0, contentW, contentH);
    self.ctrVideoView.frame = CGRectMake(0, contentH, contentW, contentH);
    self.bomVideoView.frame = CGRectMake(0, 2*contentH, contentW, contentH);

}
#pragma mark - 🔒private
- (void)playItemWithFromView:(RXXKVideoControlView *)fromView{
    [self.player removeVideo];//删除之前的视频
    //取消原来代理
    self.currentPlayView.delegate = self;
    
    //切换到播放的视图
    self.currentPlayId = fromView.videoModel.post_id;
    self.currentPlayView = fromView;
    self.currentPlayerIndex = [self indexOfModel:fromView.videoModel];
    
    //设置新视图的代理
    self.currentPlayView.delegate = self;
    
    //播放
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.player playVideoWithView:fromView.coverImageView url:fromView.videoModel.video_url];
    });
}
- (NSUInteger)indexOfModel:(RXXKVideoModel *)model{
    __block NSUInteger index = 0;
    [self.videos enumerateObjectsUsingBlock:^(RXXKVideoModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (model.post_id == obj.post_id) {
            index = idx;
        }
    }];
    return index;
}
#pragma mark - 🚪public
- (void)setUpVideoDatas:(NSArray *)videoDatas atIndex:(NSUInteger)index{
    self.index = index;
    self.currentPlayerIndex = index;
    [self.videos removeAllObjects];
    if (![videoDatas isKindOfClass:[NSArray class]]) return;
    if (videoDatas.count == 0) return;
    self.scrollView.contentSize = CGSizeMake(0, 3*RX_SCREEN_HEIGHT);
    [self.videos addObjectsFromArray:videoDatas];
    if (videoDatas.count == 1) {

        [self.ctrVideoView removeFromSuperview];
        [self.bomVideoView removeFromSuperview];
        self.scrollView.contentSize = CGSizeMake(0, RX_SCREEN_HEIGHT);
        self.topVideoView.videoModel = videoDatas.firstObject;
        [self playItemWithFromView:self.topVideoView];

    }else if (videoDatas.count == 2){
        [self.bomVideoView removeFromSuperview];
        self.topVideoView.videoModel = videoDatas.firstObject;
        self.ctrVideoView.videoModel = videoDatas.lastObject;
        self.scrollView.contentSize = CGSizeMake(0, 2*RX_SCREEN_HEIGHT);
        if (index == 1) {
            //如果是中间视图,偏移一个屏幕高度到中间视图上.
            self.scrollView.contentOffset = CGPointMake(0, RX_SCREEN_HEIGHT);
            [self playItemWithFromView:self.ctrVideoView];
        }else{
            [self playItemWithFromView:self.topVideoView];
        }
    }else{
        if (index == 0) {
            self.topVideoView.videoModel = videoDatas[index];
            self.ctrVideoView.videoModel = videoDatas[index+1];
            self.bomVideoView.videoModel = videoDatas[index+2];
            [self playItemWithFromView:self.topVideoView];
        }else if (index == videoDatas.count -1){
            self.scrollView.contentOffset = CGPointMake(0, 2*RX_SCREEN_HEIGHT);
            self.bomVideoView.videoModel = videoDatas[index];
            self.ctrVideoView.videoModel = videoDatas[index-1];
            self.topVideoView.videoModel = videoDatas[index-2];
            [self playItemWithFromView:self.bomVideoView];
        }else{
            self.scrollView.contentOffset = CGPointMake(0, RX_SCREEN_HEIGHT);
            self.ctrVideoView.videoModel = videoDatas[index];
            self.bomVideoView.videoModel = videoDatas[index+1];
            self.topVideoView.videoModel = videoDatas[index-1];
            [self playItemWithFromView:self.ctrVideoView];
        }
    }
}
- (void)pause{
    if (self.player.isPlaying) {
        self.isPlaying_beforeScroll = YES;
    }else{
        self.isPlaying_beforeScroll = NO;
    }
     [self.player pausePlay];
}
- (void)resume{
    if (self.isPlaying_beforeScroll) {
        [self.player resumePlay];
    }
}
- (void)destroyPlayer{
    self.scrollView.delegate = nil;
    [self.player removeVideo];
}
#pragma mark - 🍐delegate
#pragma mark -ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.videos.count <= 3)return;
    if (self.index == 0 && scrollView.contentOffset.y <= RX_SCREEN_HEIGHT) return;
    if(self.index == self.videos.count-1 && scrollView.contentOffset.y > RX_SCREEN_HEIGHT) return;
    //上滑
    if (scrollView.contentOffset.y >= 2*RX_SCREEN_HEIGHT) {
        [self.player removeVideo]; //防止多闪
        if (self.index == 0) {//首次上滑
            self.index += 2;
             self.scrollView.contentOffset = CGPointMake(0, RX_SCREEN_HEIGHT);
            self.topVideoView.videoModel = self.ctrVideoView.videoModel;
            self.ctrVideoView.videoModel = self.bomVideoView.videoModel;
        }else{
            self.index += 1;
            if (self.index == self.videos.count - 1) {
                self.ctrVideoView.videoModel = self.videos[self.index-1];
            }else{
                self.scrollView.contentOffset = CGPointMake(0, RX_SCREEN_HEIGHT);
                self.topVideoView.videoModel = self.ctrVideoView.videoModel;
                self.ctrVideoView.videoModel = self.bomVideoView.videoModel;
            }
        }
        if (self.index < self.videos.count - 1) {
            self.bomVideoView.videoModel = self.videos[self.index+1];
        }
    }else if (scrollView.contentOffset.y <= 0 ){ //下滑
        [self.player removeVideo];
        if (self.index == 1) {
            self.topVideoView.videoModel = self.videos[self.index-1];
            self.ctrVideoView.videoModel = self.videos[self.index];
            self.bomVideoView.videoModel = self.videos[self.index+1];
            self.index -= 1;
        }else{
            if (self.index == self.videos.count -1) {
                self.index -= 2;
            }else{
                self.index -= 1;
            }
            self.scrollView.contentOffset = CGPointMake(0, RX_SCREEN_HEIGHT);
            self.bomVideoView.videoModel = self.ctrVideoView.videoModel;
            self.ctrVideoView.videoModel = self.topVideoView.videoModel;

            if (self.index > 0) {
                self.topVideoView.videoModel = self.videos[self.index-1];
            }
        }
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y == 0) {
        if (self.currentPlayId == self.topVideoView.videoModel.post_id) return;
        [self playItemWithFromView:self.topVideoView];
    }else if (scrollView.contentOffset.y == RX_SCREEN_HEIGHT){
        if(self.currentPlayId == self.ctrVideoView.videoModel.post_id) return;
        [self playItemWithFromView:self.ctrVideoView];
    }else if (scrollView.contentOffset.y == 2*RX_SCREEN_HEIGHT){
        if(self.currentPlayId == self.bomVideoView.videoModel.post_id) return;
        [self playItemWithFromView:self.bomVideoView];
    }
}
#pragma mark - RXXKVideoPlayerDelegate
- (void)player:(RXXKVideoPlayer *)player statusChanged:(RXXKVideoPlayerStatus)status{
    switch(status){
        case RXXKVideoPlayerStatusUnload:{// 未加载
            
        }
            break;
        case RXXKVideoPlayerStatusPrepared:{// 准备播放
            
        }
            break;
        case RXXKVideoPlayerStatusLoading:{// 加载中
            [self.currentPlayView startLoading];
            [self.currentPlayView hidePlayBtn];
        }
            break;
        case RXXKVideoPlayerStatusPlaying:{//播放中
            [self.currentPlayView stopLoading];
            [self.currentPlayView hidePlayBtn];
        }
            break;
        case RXXKVideoPlayerStatusPaused:{//暂停
            [self.currentPlayView stopLoading];
            [self.currentPlayView showPlayBtn];
        }
            break;
        case RXXKVideoPlayerStatusEnded:{//播放完成
            //重新开始播放
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.player resetPlay];
            });
        }
            break;
        case RXXKVideoPlayerStatusError:{//播放错误
            
        }
            break;
        default:
            break;
    }
}
- (void)player:(RXXKVideoPlayer *)player currentTime:(float)currentTime totalTime:(float)totalTime progress:(float)progress{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.currentPlayView setProgress:progress];
    });
}
#pragma mark - RXXKVideoControlViewDelegate
- (void)contentViewDidClickSelf:(RXXKVideoControlView *)contentView{
    if (self.player.isPlaying) {
        [self.player pausePlay];
    }else{
        [self.player resumePlay];
    }
}
- (void)contentViewDidClickIcon:(RXXKVideoControlView *)contentView{
    //点击头像
}
- (void)contentViewDidClickPraise:(RXXKVideoControlView *)contentView{
    //点赞
}
- (void)contentViewDidClickCommit:(RXXKVideoControlView *)contentView{
    //点击评论
}
- (void)contentViewDidClickShare:(RXXKVideoControlView *)contentVIew{
    //点击分享
}
#pragma mark - 🔄overwrite
#pragma mark - ☎️notification
#pragma mark - 🎬event response
#pragma mark - ☸getter and setter
- (GKDYVideoViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [GKDYVideoViewModel new];
    }
    return _viewModel;
}
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.bounces = NO;
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.delegate = self;
        [_scrollView addSubview:self.topVideoView];
        [_scrollView addSubview:self.ctrVideoView];
        [_scrollView addSubview:self.bomVideoView];
        [_scrollView setContentSize:CGSizeMake(0,3*RX_SCREEN_HEIGHT)];
        if (@available(iOS 11.0, *)) {
            _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    return _scrollView;
}
- (RXXKVideoControlView *)topVideoView{
    if (!_topVideoView) {
        _topVideoView = [RXXKVideoControlView new];
    }
    return _topVideoView;
}
- (RXXKVideoControlView *)ctrVideoView{
    if (!_ctrVideoView) {
        
        _ctrVideoView = [RXXKVideoControlView new];
    }
    return _ctrVideoView;
}
- (RXXKVideoControlView *)bomVideoView{
    if (!_bomVideoView) {
        _bomVideoView = [RXXKVideoControlView new];
    }
    return _bomVideoView;
}
- (NSMutableArray *)videos{
    if (!_videos) {
        _videos = [NSMutableArray array];
    }
    return _videos;
}
- (RXXKVideoPlayer *)player{
    if (!_player) {
        _player = [RXXKVideoPlayer new];
        _player.delegate = self;
    }
    return _player;
}
@end
